<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== InArch ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 22.04.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/
    
    /***
    * Class adminSiteStructure
    ****
    * Needs Description
    ****
    * @package adminModules
    * @author A Kulikov <a.kulikov@gmail.com>
    * @version n/a
    * @since 22.04.2005
    * @copyright essentialmind.com 2005
    ***/
    class adminSiteStructure extends adminModule{
        private $tree;

        /**
         * This is the router of the page, will display the tree and also
         * pass control to the POST processor
         * 
         * @return void 
         **/
        public function process(){
            //fetch the ID of the root node (used twice in this method)
            $rootNode = $this->db->getOne("SELECT id FROM structure WHERE parent_id IS NULL");

			//temp javascript supporter
			setcookie("selected",$rootNode,time()+60);

            //cast a tree
            $this->tree = new tree($this->db,'structure LEFT JOIN objectmap ON (structure.id = objectmap.nodeid)',$this->log,'id, url, level, title');

            //see if there is a submit (file upload only)
            if($_POST){
                $this->processPost();
            }

            //see if there is a get directive
            $this->processGet();
        }


        /**
         * Process POST inputs
         * 
         * @return  void 
         * @2do     error handling
         **/
        private function processPost(){
            if(isset($_FILES['fileloc'])){
                //cast objects
                $uploader   = new fileUploader();
                $myTranslit = new translitWrap();
                
                //prepare file name
                $fileName = str_replace('.','_d_o0o_t_',$_FILES['fileloc']['name']);
                $fileName = $myTranslit->UrlTranslit($fileName);
                $fileName = str_replace('_d_o0o_t_','.',$fileName);
                
                if(!empty($_GET['node'])){
                    $filePath = ROOT.'files'.DIRECTORY_SEPARATOR.'nodes'.DIRECTORY_SEPARATOR.(int)$_GET['node'].DIRECTORY_SEPARATOR;
                    $linkPath = 'files'.DIRECTORY_SEPARATOR.'nodes'.DIRECTORY_SEPARATOR.(int)$_GET['node'].DIRECTORY_SEPARATOR;
                }else{
                    $filePath = ROOT.'files'.DIRECTORY_SEPARATOR.'pages'.DIRECTORY_SEPARATOR.(int)$_GET['id'].DIRECTORY_SEPARATOR;
                    $linkPath = 'files'.DIRECTORY_SEPARATOR.'pages'.DIRECTORY_SEPARATOR.(int)$_GET['id'].DIRECTORY_SEPARATOR;
                }
                
                if($uploader->preparePath($filePath)){
                    $uploader->copyFile($_FILES['fileloc']['tmp_name'],$filePath.$fileName);
                }
                
                $fsize = ceil(filesize($filePath.$fileName)/1024);
                echo "<script language=\"JavaScript\" type=\"text/javascript\">parent.addFile('".$fileName."','".str_replace('.','_',$fileName)."','".$fsize." Kb','".(int)$_GET['node']."','".(int)$_GET['id']."','".$linkPath."'); parent.cancelUpload();</script>";
                exit;
            }
        }


        /**
         * Process GET inputs
         * 
         * @return  void 
         * @2do     error handling
         **/
        private function processGet(){
            //check if there is an action handler present
            //currently all actions are edit actions, later a
            //switch must be built in
            if(isset($_GET['action']) and (isset($_GET['id']) or isset($_GET['node']))){
                switch($_GET['action']){
                    case 'edit': { $this->editNode();      break;}
                    case 'data': { $this->editDatablock(); break;}
                }
                
            }
        }
        
        
        /**
         * Actual node content loader
         *
         */
        private function editNode(){
            
            try{
                //bogus corrent
                if(!empty($_GET['id'])){ // calling for a page edit
                    $id = (int)$_GET['id'];
                   
                    //very well, get the page type from the database
                    $codeSet = $this->db->getOne("SELECT codeset FROM pagemap LEFT JOIN datatype ON pagemap.pagetype = datatype.id WHERE pagemap.id = $id");
                }else{ // calling for a folder edit
                    
                    $id = (int)$_GET['node'];
                    
                    //very well, get the page type from the database
                    $codeSet = $this->db->getOne("SELECT 
                                                    datatype.codeset 
                                                  FROM structure
                                                  LEFT JOIN datatype ON structure.node_type = datatype.id 
                                                  WHERE structure.id = $id");
                    
                }                
                //is there a valid codeset returned?
                if($codeSet){
                    //now give all power to the controller of this datatype
                    $myNode = adminNodeFactory::cast($codeSet,$this->db,$this->smarty,$this->log);                                       
                    //do the dirty work in the class
                    $myNode->display();
                }else{
                    
                    //page not found, what to do, what to do?
                    throw new Exception("No page with the supplied ID \"$id\" in the system");   
                }             
                
                
            }catch(exception $e){
                //log error
                $this->log->recordError($e->getMessage());
                exit;
            } 
        }

        
        /**
         * All the datablock editing happens in this function
         *
         */
        private function editDatablock(){
            
            //change request?
            if($_POST){
                //check bogus data
                if(empty($_POST['title'])){
                    $_POST['title'] = 'n/a';
                }
                
                //inherit
                if($_POST['inherit']){
                    $inherit = 'true';
                }else{
                    $inherit = 'false';
                }
                
                //global
                if($_POST['global']){
                    $global = 'true';
                }else{
                    $global = 'false';
                }
                
                //make sure the tag is small
                $_POST['tag'] = strtolower($_POST['tag']);
                                
                //database insert/update
                if(empty($_GET['block'])){
                    
                    //insert
                    $this->db->Execute("INSERT INTO datablocks(title, content, tag, global) VALUES('".$_POST['title']."','".$_POST['content']."','".$_POST['tag']."',$global)");
                    $_GET['block'] = (int)$this->db->getOne("SELECT last_value FROM datablocks_id_seq");
                    
                    //now need to make a relationship
                    if((int)$_GET['page']>0){
                        $this->db->Execute("INSERT INTO datablock_page_mapping(blockid,pageid) VALUES(".(int)$_GET['block'].",".(int)$_GET['page'].")");
                    }else{
                        $this->db->Execute("INSERT INTO datablock_node_mapping(blockid,nodeid,inherit) VALUES(".(int)$_GET['block'].",".(int)$_GET['node'].",$inherit)");
                    }
                    
                    //tell smarty to load some javascript
                    $this->smarty->assign('newBlock',true);
                }else{
                    //let the template know what the name of the old tag is
                    $this->smarty->assign('oldTag',$this->db->getOne("SELECT tag FROM datablocks WHERE id = ".(int)$_GET['block']));
                    
                    $this->db->Execute("UPDATE datablocks SET title = '".$_POST['title']."', content = '".$_POST['content']."', global = $global WHERE id = ".(int)$_GET['block']);
                    
                    //now need to make a relationship
                    if((int)$_GET['page']>0){
                        $this->db->Execute("UPDATE datablock_page_mapping SET inherit = $inherit WHERE blockid = ".(int)$_GET['block']." AND pageid = ".(int)$_GET['page']);
                    }else{
                        $this->db->Execute("UPDATE datablock_node_mapping SET inherit = $inherit WHERE blockid = ".(int)$_GET['block']." AND nodeid = ".(int)$_GET['node']);    
                    }
                    
                    //tell smarty to load some javascript
                    $this->smarty->assign('updateBlock',true);
                }
                
                //create confirmation message
                $_GET['confirm'] = true;
            }
            
            //do we have a positive block id?
            if(!empty($_GET['block'])){
                //get block data
                $this->smarty->assign("data",$this->db->getRow("SELECT * FROM datablocks WHERE id = ".(int)$_GET['block']));
                
                //is this a local edit?
                if(!empty($_GET['page'])){
                    $mapping = $this->db->getRow("SELECT * FROM datablock_page_mapping WHERE blockid = ".(int)$_GET['block']." AND pageid = ".(int)$_GET['page']);
                }else{
                    $mapping = $this->db->getRow("SELECT * FROM datablock_node_mapping WHERE blockid = ".(int)$_GET['block']." AND nodeid = ".(int)$_GET['node']);
                }
                
                if(!$mapping){
                    $this->smarty->assign("nochange",true);
                }else{
                    if($mapping['inherit'] and $mapping['inherit'] == 't'){
                        $this->smarty->assign("inherit",true);
                    }
                }
            }
            
            echo $this->smarty->preFetch("datablock.html");
            exit;
        }
        

        /** 
         * set the action template to 404.html
         * 
         * @return void
         **/
        public function setTemplate(){
            $this->setActionTemplate('sitestructure.html');
        }
    }
?>